package com.tool.weixin.api;

import net.sf.json.JSONObject;

import org.slf4j.Logger;

import com.tool.weixin.model.WxTicket;
import com.tool.weixin.util.HttpUtils;

public class QrcodeApi {

	private static final Logger logger = org.slf4j.LoggerFactory.getLogger(QrcodeApi.class);
	
	private static final String qrcode_create_ticket = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=TOKEN";
	
	private static final String qrcode_show = "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=TICKET";
	/**临时**/
	private static final String ACTION_SCENE = "QR_SCENE";
	/**永久**/
	private static final String ACTION_LIMIT_SCENE = "QR_LIMIT_SCENE";
	/**永久字符串参数**/
	private static final String ACTION_LIMIT_STR_SCENE = "QR_LIMIT_STR_SCENE";
	
	/**
	 * 永久字符串参数 
	 * @param scene_str 长度限制为1到64
	 * @return
	 */
	public static WxTicket getTicket(String scene_str) {
		return getTicket(ACTION_LIMIT_STR_SCENE, scene_str, 0L);
	}
	/**
	 * 临时
	 * @param sceneid 32位非0整型
	 * @param seconds 秒
	 * @return
	 */
	public static WxTicket getTicket(long sceneid,long seconds) {
		return getTicket(ACTION_SCENE, sceneid, seconds);
	}
	
	/**
	 * 
	 * @param sceneid 1--100000
	 * @return
	 */
	public static WxTicket getTicket(int sceneid) {
		return getTicket(ACTION_LIMIT_SCENE, sceneid, 0L);
	}
	
	private static WxTicket getTicket(String action,Object scene,long seconds) {
		String params = null;
		if(action == ACTION_SCENE) {
			params = "{\"expire_seconds\": "+seconds+", \"action_name\": \"QR_SCENE\", \"action_info\": {\"scene\": {\"scene_id\": "+scene+"}}}";
		} else if(action == ACTION_LIMIT_SCENE) {
			params = "{\"action_name\": \"QR_LIMIT_SCENE\", \"action_info\": {\"scene\": {\"scene_id\": "+scene+"}}}";
		} else if(action == ACTION_LIMIT_STR_SCENE) {
			params = "{\"action_name\": \"QR_LIMIT_STR_SCENE\", \"action_info\": {\"scene\": {\"scene_str\": \""+scene+"\"}}}";
		}
		String requestUrl = qrcode_create_ticket.replace("TOKEN", AccessTokenApi.getAccessToken().getToken());
		JSONObject jsonObject = HttpUtils.httpRequest(requestUrl, "GET", params);
		logger.debug(jsonObject.toString());
		WxTicket ticket = new WxTicket();
		try {
			ticket.setTicket(jsonObject.getString("ticket"));
			ticket.setUrl(jsonObject.getString("url"));
			if(jsonObject.containsKey("expire_seconds ")) {
				ticket.setExpires(jsonObject.getInt("expire_seconds"));
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("创建二维码ticket失败 errcode:{} errmsg:{}", jsonObject.getInt("errcode"), jsonObject.getString("errmsg"));
		}
		return ticket;
	}
	
	public static String showQrcode(String ticket) {
		return qrcode_show.replace("TICKET", ticket);
	}
}
